import { defineComponent, computed, inject, ref, createVNode } from 'vue';
import { CascaderContextKey } from './index.js';
import Checkbox from '../../inner/Checkbox.js';
import Loading from '../../inner/Loading.js';
import { FeatherChevronRight } from 'cui-vue-icons/feather';

const Item = /* @__PURE__ */ defineComponent({
  name: 'CascaderItem',
  props: {
    data: {
      type: Object
    },
    store: {
      type: Object
    },
    trigger: {
      type: String
    }
  },
  setup(props) {
    const store = props.store;
    const valueField = store.valueField || 'value';
    const titleField = store.titleField || 'title';
    const selected = computed(() => {
      return store.selectedKey.value?.includes(props.data[valueField]);
    });
    const classList = computed(() => ({
      'cm-cascader-item': true,
      'cm-cascader-item-active': selected.value,
      'cm-cascader-item-disabled': props.data.disabled
    }));
    const ctx = inject(CascaderContextKey, {});
    const loading = ref(false);
    const onClick = async () => {
      if (props.data.disabled) {
        return;
      }
      if (props.data.loading && ctx && ctx.loadData) {
        try {
          loading.value = true;
          await store.loadData(props.data, ctx.loadData);
        } catch (e) {
          // todo
        } finally {
          loading.value = false;
        }
      }
      if (props.trigger === 'click') {
        store.selectItem(props.data[valueField]);
      }
      ctx && ctx.onSelect(props.data);
    };
    let timer = null;
    const onMouseEnter = () => {
      if (props.data.disabled) {
        return;
      }
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        !selected.value && store.selectItem(props.data[valueField]);
      }, 100);
    };
    const onCheckChange = checked => {
      store.checkNode(props.data[valueField], checked);
    };
    return () => createVNode("div", {
      "class": classList.value,
      "onClick": onClick,
      "onMouseenter": props.trigger === 'hover' ? onMouseEnter : undefined
    }, [props.data.icon, ctx.multi && props.data.checkable !== false ? createVNode(Checkbox, {
      "disabled": props.data.disabled,
      "checked": props.data.checked,
      "onChange": onCheckChange
    }, null) : null, createVNode("span", {
      "class": "cm-cascader-text"
    }, [props.data[titleField]]), props.data.children && props.data.children.length || props.data.loading ? loading.value ? createVNode(Loading, {
      "color": "#1890ff"
    }, null) : createVNode(FeatherChevronRight, {
      "class": "cm-menu-submenu-cert"
    }, null) : null]);
  }
});

export { Item };
